<template>
  <div>
    <!-- {{config}}
    {{configa}} -->
    <!-- <el-button @click="refresh">refresh</el-button> -->
    
    <el-row>
      <el-form v-model="search" :inline="config.searchs.inline">
        <el-form-item v-for="s in config.searchs.items" :label="s.label" :key="s.apiField">
          <component :is="getComponentById(s.showType)" v-bind="s.showConfig" v-model="search[s.apiField]"></component>    
        </el-form-item>
        <el-button @click="doSearch">搜索</el-button>
      </el-form>
    </el-row>
    <el-row>
      <el-button v-for="b in mainButtons" :type="b.type" @click="btnClick(b)" :key="b.name">{{b.label}}</el-button>
    </el-row>
    <el-row>
      <el-table :data="tableData" border>
        <el-table-column v-for="c in config.table.columns" :label="c.label" :prop="c.field" :key="c.name">
          <template slot-scope="scope">
            <component :is="getComponentById(c.showType)" v-bind="c.showConfig" v-model="scope.row[c.field]" :row="scope.row"></component>    
          </template>
        </el-table-column>
        <el-table-column  label="操作">
          <template slot-scope="scope">
            <template  v-for="b in rowButtons">
              <!-- <el-button @click="handleClick(scope.row)" type="text" size="small">查看</el-button>
              <el-button type="text" size="small">编辑</el-button> -->
              <el-button v-if="!b.confirm" :type="b.type" :size="b.size" @click="btnClick(b,scope.row)" :key="b.name">{{b.label}}</el-button>
              <el-popconfirm v-else :title="b.confirmText" @confirm="btnClick(b,scope.row)">                
                <el-button  :type="b.type" slot="reference" :size="b.size"  :key="b.name">{{b.label}}</el-button>
              </el-popconfirm>
            </template>          
          </template>
        </el-table-column>
      </el-table>
    <!-- {{pagerconfig}} -->
      <el-pagination
        v-if="this.config.pager.enable"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagerconfig.currentPage"
        :page-sizes="pagerconfig.pageSizes"
        :page-size="pagerconfig.pageSize"
        :layout="pagerconfig.layout"
        :total="pagerconfig.total">
      </el-pagination>
    </el-row>
    <!-- 弹框 -->
    <el-dialog ref="dialog" :visible.sync="showDialog" v-if="showDialog" @close="closed" :title="dialogName">
      <router-view></router-view>
    </el-dialog>
  </div>
</template>

<script>
//根据配置对象渲染列表页 核心组件
import axios from 'axios'
export default {
  name:"listcomp",
  async created(){
    this.thisurl=this.$route.path
    // console.log('child created begin');
    this.config=this.configa
    // console.log(this.config);
    // console.log(this.configa);
    
    var rep= await axios.get("http://localhost:8811/api/ShowTypeComponente/GetAll")
    // .then(rep=>{      
    //   this.listShowTypes=rep.data.result
    // })
    this.listShowTypes=rep.data.result
    // console.log('child created end');
    var t=this
    this.$root.$on('closeDialog',function(){
      t.closeDialog()
      //todo 路由回退一级
      t.$router.push(t.thisurl) 
    })
    this.$root.$on('dialogname',function(name){
      t.setDialogName(name)
    })
  },
  mounted(){
    var t=this
    var F5_KEY_CODE = 116;    
    document.addEventListener('keydown', function(e) {      
      if (e.keyCode === F5_KEY_CODE && t.showDialog) {
        // var url=location.href
        // document.location.href = "http://localhost:8080/#/complist"
        // alert(t.thisurl)        
        t.$router.push(t.thisurl)        
      }
    })
  },
  computed:{
    mainButtons(){
      if(this.config.buttons.items)
        return this.config.buttons.items.filter(x=>!x.rowButton)
      return []
    },
    rowButtons(){
      if(this.config.buttons.items)
        return this.config.buttons.items.filter(x=>x.rowButton)
      return []
    }
  },
  methods:{
    closeDialog(){      
      this.showDialog=false
      this.refresh()
    },
    setDialogName(name){
      this.dialogName=name
    },
    setChild(name){
      console.log(name);
    },
    closed(){      
      this.$router.back()
    },
    async btnClick(b,row){      
      if(b.action=='custom'){
        var bl="abc"
        var script=b.script;
        eval(script)
      }
      if(b.action=='dialog'){
        this.showDialog=true
        var r=b.route
        var arr=r.split('/')
        var rr=""
        arr.forEach(element => {          
          if(element=="") return
          if(element[0]==":"){
            var pa=element.substring(1)
            rr+="/"+row[pa]
          }else{
            rr+="/"+element
          }
        });        
        this.$router.push(rr)
      }
      if(b.action=='route'){
        var r=b.route
        for (var k in row){
          r=r.replace("{"+k+"}",row[k])
        }
        this.$router.push(r)
      }
      if(b.action=='newpage'){
        // todo
        window.open(b.route,'_blank')
      }
      if(b.action=='callapi'){
        // todo 
        var url=b.route
        for (var k in row){
          url=url.replace("{"+k+"}",row[k])
        }
        var rep
        if(b.apimethod=='GET'){
          rep=await axios.get(url)
        }
        else{
          rep=await axios.post(url)
        }
        console.log(rep.data);
        this.refresh()
      }
      console.log('按钮被点击了');
      console.log(b);
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pagerconfig.pageSize=val      
      this.refresh()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);      
      this.pagerconfig.currentPage=val
      this.refresh()
    },
    getobjfield(obj,field){
      var arr=field.split('.')
      var root=obj;
      arr.forEach(ele=>{
        root=root[ele]
      })
      return root
    },
    getComponentById(id){      
      if(this.listShowTypes!=null && this.listShowTypes.length>0){
        return this.listShowTypes.filter(x=>x.id==id)[0].component
      }
      return ""
    },
    doSearch(){
      console.log(this.search);      
      this.pagerconfig.currentPage=1
      this.refresh()
    },
    async refresh(){
      // console.log('into refresh');      
      // console.log(this.configa);
      this.config=this.configa
      // console.log(this.config);
      if(!this.config || !this.config.api || !this.config.api.url){
        
        return
      }
      var url=this.config.api.url
      var method=this.config.api.method
      var resultField=this.config.api.resultDataField
      if(this.pagerconfig.pageSize<1){        
        this.pagerconfig.pageSize=parseInt(this.config.pager.pagesize)
      }
      var r=null
      
      if(method=='GET'){
        await axios.get(url).then(rep=>{          
          this.tableData=rep.data[resultField]          
          r=rep.data
        })
      }
      else{        
        var obj={}
        obj[this.config.pager.apiPageSizeField]=this.pagerconfig.pageSize
        obj[this.config.pager.apiCurrentPageField]=this.pagerconfig.currentPage
        // console.log(obj);
        obj[this.config.searchs.apiField]=this.search
        
        await axios.post(url,obj).then(rep=>{
          var arr=resultField.split('.')
          var root=rep.data
          arr.forEach(element => {
            root=root[element]
          });
          this.tableData=root          
          r=rep.data
        })
      }      
      if(this.config.pager.enable){
        this.pagerconfig.layout=this.config.pager.layout
        // console.log(r);
        this.pagerconfig.currentPage=this.getobjfield(r,this.config.pager.currentPageField)
        this.pagerconfig.total=this.getobjfield(r,this.config.pager.totalField)        
        this.pagerconfig.pageSize=this.getobjfield(r,this.config.pager.pageSizeField)
        this.pagerconfig.pageSizes=JSON.parse(this.config.pager.pageSizes)
        // console.log(this.pagerconfig);
      }
    }   
  },
  name:"listComp",
  props:['configa'],
  watch:{
    configa:{
      deep:true,
      handler(o,n){
        // console.log('configa is changed');
        this.config=this.configa
        this.refresh()
      }
    }
  },
  data(){
    return {
      thisurl:"",
      showDialog:false,
      dialogName:"",
      config:{},
      listShowTypes:[],
      tableData:[],
      search:{},
      pagerconfig:{
        currentPage:1,
        layout:"",
        total:0,
        pageSize:-1,
        pageSizes:[100, 200, 300, 400]
      }
    }
  }
}
</script>

<style scoped>
.el-button + span {
    margin-left: 10px;
}
span + .el-button{
  margin-left: 10px;
}
</style>